package demo.dao;

import jdbc.DBUtil;
import jdbc.UserInfo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * DAO Data Access Object
 * 数据访问对象
 * 这些类的工作就是和数据库打交道，将我们java中需要的对象映射为表中的记录
 */
public class UserMapper {
    public int insert(UserInfo userInfo){
        try (Connection connection = DBUtil.getConnection()){
            PreparedStatement ps = connection.prepareStatement(
                    "INSERT INTO userinfo(username,password,nickname,age) " +
                            "VALUES(?,?,?,?)"
            );
            ps.setString(1, userInfo.getUsername());
            ps.setString(2, userInfo.getPassword());
            ps.setString(3, userInfo.getNickname());
            ps.setInt(4, userInfo.getAge());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public UserInfo findByUsername(String username){
        try (Connection connection = DBUtil.getConnection()) {
            //验证是否为重复用户
            PreparedStatement ps = connection.prepareStatement(
                    "SELECT username,password,nickname,age " +
                            "FROM userinfo " +
                            "WHERE username=?"
            );
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                UserInfo userInfo = new UserInfo();
                userInfo.setUsername(rs.getString("username"));
                userInfo.setPassword(rs.getString("password"));
                userInfo.setNickname(rs.getString("nickname"));
                userInfo.setAge(rs.getInt("age"));
                return userInfo;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int update(UserInfo userInfo){
        try (Connection connection = DBUtil.getConnection()){
            PreparedStatement ps = connection.prepareStatement("" +
                    "UPDATE userinfo " +
                    "SET password=?,nickname=?,age=? " +
                    "WHERE username=?"
            );
            ps.setString(1, userInfo.getPassword());
            ps.setString(2, userInfo.getNickname());
            ps.setInt(3, userInfo.getAge());
            ps.setString(4, userInfo.getUsername());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
